﻿using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Data;

namespace iSun.Model
{
    public class DataTableBaseEntity : BaseEntity, IEnumerable, IEnumerator
    {
        /// <summary>
        /// 数据行
        /// </summary>
        public DataRow DRow
        {
            get;
            set;
        }

        /// <summary>
        /// 
        /// </summary>
        public DataTableBaseEntity() { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="row"></param>
        public DataTableBaseEntity(DataRow row)
        {
            this.DRow = row;
            this.DTable = DRow.Table;
        }


        /// <summary>
        ///  DataTable基类构造函数
        /// </summary>
        /// <param name="dt"></param>
        public DataTableBaseEntity(DataTable dt)
        {
            CreateDT(dt);
        }

        /// <summary>
        /// 创建非实体对象的数据结构
        /// </summary>
        /// <param name="dt">Datatable</param>
        public void CreateDT(DataTable dt)
        {
            this.DTable = dt;
            if (this.DTable.Rows.Count == 0)
            {
                this.DRow = dt.NewRow();
                this.DTable.Rows.Add(this.DRow);
            }
            else
            {
                this.DRow = dt.Rows[0];
            }
        }

        /// <summary>
        /// 创建非实体对象的数据结构
        /// </summary>
        public void CreateDT()
        {
            DataTable dt = (new iSun.DAL.DBExtend.DbSql()).ExecuteQuery("Select top 0 * from " + this.TableName);
            CreateDT(dt);
        }

        /// <summary>
        /// 创建非实体对象的数据结构
        /// </summary>
        /// <param name="id">行数据唯一KEY值</param>
        public virtual void CreateDT(object id)
        {
            DataTable dt = (new iSun.DAL.DBExtend.DbSql()).ExecuteQuery("Select top 1 * from " + this.TableName + " where  " + this.TableKey + "='" + id + "'");
            CreateDT(dt);
        }

        /// <summary>
        /// 获取配置文件中Confing的相关信息
        /// 用于处理有人工设置界面需要增加自定义信息功能
        /// </summary>
        /// <param name="tableName"></param>
        public virtual void CreateConfigDT(string tableName)
        {
            DataTable dt1 = (new iSun.DAL.DBExtend.DbSql()).ExecuteQuery("Select FieldName from Set_EditUIConfig where EntityName='" + tableName+"' and IsSysAutoSave='Y'");
            if (dt1 == null)
            {
                return;
            }
            if (dt1.Rows.Count ==0)
            {
                return;
            }
            string fields= string.Empty;
            foreach (DataRow row in dt1.Rows)
            {
                fields =fields + row.ItemArray[0].ToString()+",";
            }
            fields = fields + this.TableKey;//将关键字付上
            DataTable dt = (new iSun.DAL.DBExtend.DbSql()).ExecuteQuery("Select top 0 " + fields + " from " + this.TableName);
            CreateDT(dt);
            this.IsSysAutoSave = true;
            //DataTable dt 
        }


        /// <summary>
        /// 是否系统自动保存
        /// </summary>
        public bool IsSysAutoSave
        {
            get;
            set;
        }


        /// <summary>
        /// 创建DataTable对象
        /// </summary>
        public virtual void CreateDataTable()
        {
            DataTable dt = (new iSun.DAL.DBExtend.DbSql()).ExecuteQuery("Select top 0 * from " + this.TableName);
            CreateDT(dt);
        }

        /// <summary>
        /// 根据表名创建DataTable对象
        /// </summary>
        /// <param name="tableName">表名</param>
        public virtual void CreateDataTable(string tableName)
        {
            DataTable dt = (new iSun.DAL.DBExtend.DbSql()).ExecuteQuery("Select top 0 * from " + tableName);
        }


        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        public virtual bool Delete(string id)
        {
           int i =  (new iSun.DAL.DBExtend.DbSql()).RunSqlCommand("Delete from " + this.TableName + " where  " + this.TableKey + "='" + id + "'");
           return i > 0;
        }
        //public bool DeleteData(string id)
        //{

        //}
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string GetTableId()
        {
            object[] o = new object[1];
            o[0] = this;
            object instance = CreateInstance("iSun.BLL.Base.BaseBussnies", "iSun.Bussiness.Base", o);
            
            Type t = instance.GetType();
            object obj = t.InvokeMember("GetGuids", BindingFlags.Default | BindingFlags.InvokeMethod
                        , null, instance, null);
            return obj as string;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public virtual string[] GetKey()
        {
            object[] o = new object[1];
            o[0] = this;
            object instance = CreateInstance("iSun.BLL.Base.BaseBussnies", "iSun.Bussiness.Base", o);
            Type t = instance.GetType();
            object obj = t.InvokeMember("GetKey", BindingFlags.Default | BindingFlags.InvokeMethod
                        , null, instance, null);
            return obj as string[];
        }



        /// <summary>
        /// 创建实例
        /// </summary>
        /// <param name="TypeName">类型名</param>
        /// <param name="AssemblyName">动态库命</param>
        /// <returns>实例对象</returns>
        private  object CreateInstance(string TypeName, string AssemblyName)
        {
            Assembly assem = Assembly.Load(AssemblyName);
            object obj = CreateInstance(TypeName, assem);
            return obj;
        }
        private  object CreateInstance(string TypeName, string AssemblyName, object[] o)
        {
            Assembly assem = Assembly.Load(AssemblyName);
            object obj = CreateInstance(TypeName, assem,o);
            return obj;
        }
        /// <summary>
        /// 创建实例
        /// </summary>
        /// <param name="TypeName">类型名</param>
        /// <param name="assembly">动态库</param>
        /// <returns>实例对象</returns>
        private  object CreateInstance(string TypeName, Assembly assembly)
        {
            try
            {
                Type t = assembly.GetType(TypeName);
                if (t == null)
                {
                    t = assembly.GetType(assembly.GetName().Name + "." + TypeName);
                }
                object obj = Activator.CreateInstance(t);
                return obj;
            }
            catch (System.Exception e)
            {
                throw e;
            }

        }

        /// <summary>
        /// 创建实例
        /// </summary>
        /// <param name="TypeName">类型名</param>
        /// <param name="assembly">动态库</param>
        /// <returns>实例对象</returns>
        private object CreateInstance(string TypeName, Assembly assembly, object[] o)
        {
            try
            {
                Type t = assembly.GetType(TypeName);
                if (t == null)
                {
                    t = assembly.GetType(assembly.GetName().Name + "." + TypeName);
                }
                object obj = Activator.CreateInstance(t,o);
                return obj;
            }
            catch (System.Exception e)
            {
                throw e;
            }

        }

        /// <summary>
        /// 将数据装入字典
        /// </summary>
        /// <returns></returns>
        public virtual SortedDictionary<string, object> GetFieldValueList()
        {
            SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
            for (int i = 0; i <DTable.Columns.Count;i++ )
            {
                string field = DTable.Columns[i].ColumnName;
                dic.Add(field, DRow[field]);
            }
            return dic;
        }

        /// <summary>
        /// 获取DT结构
        /// </summary>
        /// <returns></returns>
        public virtual SortedDictionary<string, object> GetFiledList()
        {
            SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
            for (int i = 0; i < DTable.Columns.Count; i++)
            {
                string field = DTable.Columns[i].ColumnName;
                dic.Add(field, DTable.Columns[i].DataType.ToString());
            }
            return dic;
        }

        public virtual Dictionary<string, object> FieldValue
        {
            get;
            set;
        }

        /// <summary>
        /// 设列值
        /// </summary>
        /// <param name="key">列名</param>
        /// <param name="value">值</param>
        public  virtual void SetValue(string key, object value)
        {
            DRow[key] = value;
        }


        public virtual void SetValue(Dictionary<string, object> fieldValue)
        {
            SortedDictionary<string, object> list = GetFiledList();
            foreach (var item in fieldValue)
            {
                string fType = list[item.Key] as string;
                object o = item.Value;
                switch (fType)
                {
                    case "System.String":
                        o = item.Value;
                        break;
                    case "System.Decimal":
                        try
                        {
                            o = System.Decimal.Parse(item.Value.ToString());
                        }
                        catch { o = 0.0; }
                        break;
                    case "System.Int32":
                        try
                        {
                            o = System.Int32.Parse(item.Value.ToString());
                        }
                        catch { o = 0; }
                        break;
                    case "System.DateTime":
                        try
                        {
                            o = System.DateTime.Parse(item.Value.ToString());
                        }
                        catch { o = System.DateTime.Parse("1900-01-01"); }
                        break;
                    case "System.Guid":
                        try
                        {
                            if ((item.Value as string) == "")
                            {
                                o = Guid.Empty;
                            }
                            else
                            {
                                o = System.Guid.Parse(item.Value.ToString());
                            }
                        }
                        catch { o = Guid.Empty; }
                        break;
                    case "System.Int64":
                        try
                        {
                            o = System.Int64.Parse(item.Value.ToString());
                        }
                        catch { o = 0.0; }
                        break;
                    case    "System.Boolean":
                        try
                        {
                            o = System.Boolean.Parse(item.Value.ToString());
                        }
                        catch { o = false; }
                        break;
                    case "System.Double":
                        try
                        {
                            o = System.Double.Parse(item.Value.ToString());
                        }
                        catch { o = 0; }
                        break;
 
                    default:
                        break;
                }
                SetValue(item.Key, o);
            }
        }



        public object this[string key]
        {
            get
            {
                if (DRow[key] == null)
                {
                    throw new Exception("不存在列名:" + key);
                }
                return DRow[key];
            }
            set
            {
                if (DRow[key] != this[key])
                {
                    DRow[key] = this[key];
                }
            }
        }
        

        /// <summary>
        /// 实体对应的JSON
        /// </summary>
        public virtual string EntityJson
        {
            get;
            set;
        }


        public virtual DataTable DTable
        {
            get;
            set;
        }


        public virtual void AddColums(string field, string dataType)
        {
            switch (dataType)
            {
                case "string":
                    DTable.Columns.Add(field, Type.GetType("System.String"));
                    break;
                case "guid":
                    DTable.Columns.Add(field, Type.GetType("System.Guid"));
                    break;
                case "datetime":
                    DTable.Columns.Add(field, Type.GetType("System.DateTime"));
                    break;
                case "int":
                    DTable.Columns.Add(field, Type.GetType("System.Int32"));
                    break;
                case "long":
                    DTable.Columns.Add(field, Type.GetType("System.Int64"));
                    break;
                case "bool":
                    DTable.Columns.Add(field, Type.GetType("System.Boolean"));
                    break;
                case "number":
                    DTable.Columns.Add(field, Type.GetType("System.Double"));
                    break;
                default:
                    DTable.Columns.Add(field, Type.GetType("System.String"));
                    break;

            }
        }

        public virtual DataTable DataTableNew()
        {
            return new DataTable();
        }

        /// <summary>
        /// 表KEY
        /// </summary>
        public virtual string TableKey
        {
            get;
            set;
        }

        public virtual string KeyType
        {
            get;
            set;
        }
        /// <summary>
        /// 表名
        /// </summary>
        public virtual string TableName
        {
            get;
            set;
        }

        /// <summary>
        /// 
        /// </summary>
        public virtual Guid TableGuidKey
        {
            get
            {
                if (TableKey.IndexOf("-") > -1)
                {
                    return Guid.Parse(TableKey);
                }
                return Guid.NewGuid();
            }
        }


        /// <summary>
        /// 
        /// </summary>
        public virtual int TableIntKey
        {
            get
            {
                if (TableKey.IndexOf("-") < 0)
                {
                    return int.Parse(TableKey);
                }
                return 0;
            }
        }

        /// <summary>
        /// 记录数
        /// </summary>
        public virtual int Count
        {
            get
            {
                return DTable == null ? 0 : DTable.Rows.Count;
            }
        }

        public virtual IEnumerator GetEnumerator()
        {
            return (IEnumerator)this;
        }

        public int _Current = -1;
        public virtual object Current
        {
            get
            {
                return new DataTableBaseEntity(DTable.Rows[_Current]);
            }
        }

        public virtual bool MoveNext()
        {
            if (_Current < DTable.Rows.Count - 1 && DTable.Rows.Count >= 1)
            {
                _Current++;
                return true;
            }
            else
            {
                _Current = -1;
                return false;
            }
        }

        public virtual void Reset()
        {
            _Current = -1;
        }

    }
}
